#!/usr/bin/env bash

# Python 获取微信公众号文章链接参数
# 1. __biz
# 2. album_id
# def get_url_param(url: str, param: str) -> str | None:
#     return parse_qs(urlsplit(url).query).get(param, [None])[0]

# get_param() {
#   python3 -c "from urllib.parse import urlsplit, parse_qs; import sys; print(parse_qs(urlsplit(sys.argv[1]).query).get(sys.argv[2], [''])[0])" "$1" "$2"
# }

# Shell 获取微信公众号文章并制作数据集
# 1. 准备初始信息
biz="MzA5NzE0Mjg4Ng=="
album_id="3054359217224204292"

# 2. 初始数据
curl "https://mp.weixin.qq.com/mp/appmsgalbum?__biz=${biz}&action=getalbum&album_id=${album_id}&f=json" | jq '.getalbum_resp.article_list[]' -r > data.json

# 3. 获取最后一条消息id
msgid=$(curl "https://mp.weixin.qq.com/mp/appmsgalbum?__biz=${biz}&action=getalbum&album_id=${album_id}&f=json" | jq '.getalbum_resp.article_list[-1]' | jq .msgid -r)
itemidx=$(curl "https://mp.weixin.qq.com/mp/appmsgalbum?__biz=${biz}&action=getalbum&album_id=${album_id}&f=json" | jq '.getalbum_resp.article_list[-1]' | jq .itemidx -r)

while true; do

    if [[ -z "$msgid" || "$msgid" == "null" ]]; then
        break
    fi

    curl "https://mp.weixin.qq.com/mp/appmsgalbum?__biz=${biz}&action=getalbum&album_id=${album_id}&count=10&begin_msgid=${msgid}&begin_itemidx=${itemidx}&f=json" | jq '.getalbum_resp.article_list | if type == "array" then .[-1] else . end' -r >> data.json
    tmp1=$(curl "https://mp.weixin.qq.com/mp/appmsgalbum?__biz=${biz}&action=getalbum&album_id=${album_id}&count=10&begin_msgid=${msgid}&begin_itemidx=${itemidx}&f=json" | jq '.getalbum_resp.article_list | if type == "array" then .[-1] else . end' | jq .msgid -r)
    tmp2=$(curl "https://mp.weixin.qq.com/mp/appmsgalbum?__biz=${biz}&action=getalbum&album_id=${album_id}&count=10&begin_msgid=${msgid}&begin_itemidx=${itemidx}&f=json" | jq '.getalbum_resp.article_list | if type == "array" then .[-1] else . end' | jq .itemidx -r)
    
    msgid="$tmp1"
    itemidx="$tmp2"
    curl "https://mp.weixin.qq.com/mp/appmsgalbum?__biz=${biz}&action=getalbum&album_id=${album_id}&count=10&begin_msgid=${msgid}&begin_itemidx=${itemidx}&f=json" | jq '.getalbum_resp.article_list | if type == "array" then .[-1] else . end'
    echo "url: https://mp.weixin.qq.com/mp/appmsgalbum?__biz=${biz}&action=getalbum&album_id=${album_id}&count=10&begin_msgid=${msgid}&begin_itemidx=${itemidx}&f=json"
    echo "msgid: $msgid"
    echo "itemidx: $itemidx"
done


# cat data.json | jq -s '.[-1].create_time | tonumber | strftime("%Y-%m-%d %H:%M:%S")'
